<template>
	<view>
		<cu-custom style="height: 0px;" bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			 <block slot="content">维修工单</block>
		</cu-custom>
		<view class="content">
			<!-- <view class="chooseBox">
				<view class="titleleftBox">
					<view class="choose">选择备件</view>
					<view class="rapid">点击选择</view>
				</view>
				<view class="select-icon"></view>
			</view> -->
			<view class="chooseBox">
				<view class="titleleftBox">
					<view class="choose"><text style="color:red;margin-right: 4rpx;">*</text>点位</view>
					<view @click="showQrcodeSelect()" class="rapid">{{selectQrcodeEntity.id?selectQrcodeEntity.name:'点击选择'}}</view>
					<pickerSearch v-model="qrcodeSeleceShow" :dataSource='qrcodeArry' :pickerValues="[0]" @recload='confirmQrcode'></pickerSearch>
				</view>
				<!-- <view class="select-icon"></view> -->
				<view @click="showQrcodeChoose()" class="titlerightBox text-blue">
					<text class="bxImg cuIcon-filter text-blue" style="margin-right: 10rpx;height: 18rpx;width: 18rpx;"></text>
					分类/位置
				</view>
			</view>
			<view v-if="ShowSecondQrcodeDevice==1" class="chooseBox">
				<view class="titleleftBox" style="height: 40rpx;width: 100%;">
					<view class="choose"><text style="color:red;margin-right: 4rpx;opacity: 0;">*</text>设备</view>
					<xm-cascader style="width: 70%;margin-left: 10rpx;margin-top: 2rpx;" :border="false" :showAllLevels="true" :clearable="false" 
					:checkStrictly="false" v-model="chooseDeviceValue" :options="qrcodeDeviceList"></xm-cascader>
				</view>
			</view>
			<view v-if="AddSceneChooseUserShow==1" class="chooseBox">
				<view class="titleleftBox">
					<view class="choose">维修人</view>
					<view @click="chooseSceneUsers" class="rapid">{{SceneUserChooseStatus}}</view>
				</view>
				<view @click="chooseSceneUsers" class="select-icon"></view>
			</view>
			<!-- <view class="chooseBoxTextArea">
				<view class="titleleftBox">
					<view @click="chooseSceneExperience()" class="choose">
						<view class="chooseLeft"><text style="color:red;margin-right: 4rpx;">*</text>描述</view>
						<view class="chooseMiddle text-blue"><text class="bxImg cuIcon-read text-blue" style="margin-right: 10rpx;height: 18rpx;width: 18rpx"></text>语音转文字</view>
						<view class="chooseRight text-blue"><text class="bxImg cuIcon-read text-blue" style="margin-right: 10rpx;height: 18rpx;width: 18rpx"></text>故障库</view>
					</view>
					<textarea v-model="SceneDesc" class="descTextArea" placeholder="请输入问题描述"/>
				</view>
			</view> -->
			<view class="chooseBoxTextArea">
				<view class="titleleftBox">
					<view class="choose">
						<view class="chooseLeft"><text style="color:red;margin-right: 4rpx;">*</text>描述</view>
						<view class="chooseRightContainer">
							<!-- <view @click="showWechatSI()" class="chooseMiddle text-blue"><text class="bxImg cuIcon-notification text-blue" style="margin-right: 10rpx;height: 18rpx;width: 18rpx"></text>语音转文字</view> -->
							<view @click="chooseSceneExperience()" class="chooseRight text-blue"><text class="bxImg cuIcon-read text-blue" style="margin-right: 10rpx;height: 18rpx;width: 18rpx"></text>故障库</view>
						</view>
					</view>
					<textarea v-model="SceneDesc" class="descTextArea" placeholder="请输入问题描述"/>
					<!-- 新增“按住说话”按钮 -->
					<view class="holdToTalkButton" @touchstart="streamRecord" @touchend="streamRecordEnd" >
						<text class="bxImg cuIcon-voicefill" style="margin-right: 10rpx;height: 24rpx;width: 24rpx;font-size: #333;"></text>
						按住说话（AI语音转文字）
					</view>
				</view>
			</view>
			<view v-if="IsQrcodeSceneRecodrd==1" class="chooseBox">
				<view class="titleleftBox">
					<view class="choose"><text style="color:white;margin-right: 4rpx;">*</text>录音</view>
					<view v-if="RecordData==''" @tap="ShowRecordModal" class="rapid"><text class="cuIcon-notificationfill text-black"></text>点击录音 </view>
					<view v-if="RecordData!=''" @tap="ShowRecordModal" class="rapid"><text class="cuIcon-roundcheckfill text-green"></text>已录制，点击查看录音 </view>
					<!-- 🎤 -->
				</view>
				<view  class="titlerightBox text-red">
					
				</view>
			</view>
			<view v-if="showPhone" class="chooseBoxPhone">
				<view class="titleleftBox">
					<view class="choose"><text v-if="phoneVerify" style="color:red;margin-right: 4rpx;opacity: 1;">*</text>手机号</view>
					<view v-if='requestData.Phone' class="rapid">
						<input class="uni-input" v-model="requestData.Phone" />
					</view>
					<button v-if='!requestData.Phone' class="rapid" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">一键获取</button>
				</view>
			</view>
			<active-form style="width:100% !important;" :formDate.sync="formData" num></active-form>
			<view class="padding-lr flex margin-top-sm" style="justify-content: space-between;height: 220rpx;">
			</view>
			<view class="publish-goods-wrap">
				<view :disabled="isButtonDisabled1" class="publish-goods-btn" @click="sub">提交</view>
			</view>
		</view>
		<ba-tree-picker ref="treePicker" :multiple='true' @select-change="selectAssign" title="选择部门/人员"
		     :localdata="treeUserList" valueKey="id" textKey="name" childrenKey="children" />
			 
		 <view class="cu-modal bottom-modal" :class="RecordModalName=='RecordModal'?'show':''">
			<view class="cu-dialog" style="background-color: white;">
				<view class="padding-xl" style="padding: 20rpx !important;padding-bottom: 60rpx !important;">
					<sound-recording showTop='true' duration='20' theme='#32b99d' maximum='20' confirmText='确认' @reset='resetRecord' @confirm="confirmRecord" @cancel="cancelRecord" width='60rpx' height='60rpx'></sound-recording>
				</view>
			</view>
		 </view>
		 <!-- 语音动画 -->
		 <view class="prompt" v-if="animation">
		 	<section class="dots-container">
		 		<view class="dot"></view>
		 		<view class="dot"></view>
		 		<view class="dot"></view>
		 		<view class="dot"></view>
		 		<view class="dot"></view>
		 	</section>
		 	<text>录音中...</text>
		 </view>
	</view>
</template>

<script>
import ActiveForm from "@/components/active-form/active-form";
import pickerSearch from "@/components/picker-search/pickerSearch.vue";
import request from '@/common/request.js';
import QQMapWX from "@/common/qqmap-wx-jssdk";
import soundRecording from '@/components/sound-recording/sound-recording.vue'
const plugin = requirePlugin("WechatSI")
let voiceManager = plugin.getRecordRecognitionManager()
export default {
  components: {
    ActiveForm,
	pickerSearch,
	soundRecording
  },
  data() {
    return {
		animation:false,
		RecordData:'',
		RecordModalName:'',
		IsQrcodeSceneRecodrd:0,
		isButtonDisabled1:false,
		showPhone:false,  //是否需要手机号
		phoneVerify:false, //手机号必填
		ShowSecondQrcodeDevice:0,
		chooseDeviceValue:'',
		qrcodeDeviceList:[],
		qrcodeArry: [],
		qrcodeSeleceShow: false,
		selectQrcodeEntity:{
			id:'',
			name:''
		},
		SceneDesc:'',
		treeUserList:[],
		AddSceneChooseUserShow:0,
		SceneUserIds:[],
		SceneUserChooseStatus:'点击选择',
		count:9,
		Location:{
			latitude:'',
			longitude:'',
			address:''
		},
		JobStorage:{
			JobId:'',
			JobName:''
		},
		qrcodeList:[],
		requestData:{
			JobId:'',
			Longitude:'',
			Latitude:'',
			Desc:'',
			QrcodeId:'',
			SceneType:'',
			Images:[],
			Video:'',
			CustomFields:'',
			DeviceId:'',
			Phone:''
		},
		session_key:'',
        formData: [
			// {
			// 	id: "asdfdfgd",
			// 	placeholder: "拍摄照片",
			// 	label: "拍摄照片 ",
			// 	type: "imageMulti",
			// 	counts:6,
			// 	watermark: {
			// 		UserName: '',
			// 		JobName: '工单水印',
			// 		nowTime: '',
			// 		address: '',
			// 		jingweidu: '',
			// 		customerName: '',
			// 		fileType: 999, //999工单，967 巡检强制拍照，968 巡检答题拍照，969 维保图片
			// 		chooseAlbum: true,
			// 		onlyShow:'false',
			// 	},
			// 	rules: {
			// 		name: "photo1",
			// 		imagesList:['','','','','',''],
			// 		value: "",
			// 		verify: false,
			// 		errMess: "拍摄照片1",
			// 	},
			// },
			{
				id: "asdfdfgd",
				placeholder: "拍摄照片",
				label: "拍摄照片 ",
				type: "image",
				watermark: {
					UserName: '',
					JobName: '工单水印',
					nowTime: '',
					address: '',
					jingweidu: '',
					customerName: '',
					fileType: 999, //999工单，967 巡检强制拍照，968 巡检答题拍照，969 维保图片
					chooseAlbum: true,
					onlyShow:'false',
				},
				rules: [{
					name: "photo1",
					value: "",
					verify: false,
					errMess: "拍摄照片1",
				}, {
					name: "photo2",
					value: "",
					verify: false,
					errMess: "拍摄照片2",
				}, {
					name: "photo3",
					value: "",
					verify: false,
					errMess: "拍摄照片3",
				}],
			},
			
			{
				id: "asdf111gd",
				placeholder: "拍摄视频",
				label: "拍摄视频 ",
				type: "video",
				url: '',
				onlyShow:'false',
				rules: {
					name: "video",
					value: "",
					verify: false,
					errMess: "拍摄视频",
				},
			}, {
				id: "sada55sgh",
				placeholder: "请选择维修类型",
				label: "维修类型",
				type: "radio",
				list: [{
						value: "故障",
						label: "故障",
					},
					{
						value: "计划",
						label: "计划",
					},
					{
						value: "大修",
						label: "大修",
					}
				],
				rules: {
					name: "SceneType",
					value: "故障", //字段值 0 1
					label: "故障", //名字
					verify: true,
					errMess: "请选择维修类型",
				},
			}
		],
    };
  },
	onLoad(option){
		let that=this
		that.onloadCheckRecordAuth()
		let QrcodeId=option.qrcodeid
		if(QrcodeId != '' && QrcodeId != undefined && QrcodeId != null){
			that.requestData.QrcodeId=QrcodeId
		}
		let Desc=option.Desc
		if(Desc != '' && Desc != undefined && Desc != null){
			that.SceneDesc=Desc
		}
		that.getQrcodeList()
		//that.getSetting()
		//获取位置和缓存
		//that.getLocationAndStorageSync()
		//先获取 getLocationAndStorageSync 再走GetBaseConfig
		
		
		that.GetBaseConfig(that.requestData.QrcodeId).then(() => {
			that.getWaterMarkSettings();
		});
		
		
		uni.$on('ExperienceDesc',function(data){
			//console.log('传过来的data：'+data)
			that.SceneDesc=that.SceneDesc+data
		})
		
		//点位分类筛选
		uni.$on('ChoiseQrcode',function(selectQrcodeEntity){
			if(selectQrcodeEntity.id!=null&&selectQrcodeEntity.id!=''){
				//console.log(1111111111)
				that.selectQrcodeEntity.id=selectQrcodeEntity.id
				that.selectQrcodeEntity.name=selectQrcodeEntity.name
				
				that.GetQrcodeDeviceList(selectQrcodeEntity.id)
				
			}
		})
		
		that.initRecord()
	},
	onShow: function() {
	},
	//uni.$emit 和 uni.$on属于全局跨页面传参，在接收值页面要在onUnload周期添加移除监听时间。
	onUnload() {
		uni.$off('ExperienceDesc')
		uni.$off('ChoiseQrcode')
	},
	created() {
		let that=this
	},
	mounted() {
		let that=this
	},
    methods: {
		streamRecord() {
			//console.log('开始录音')
			this.animation = true
			voiceManager.start({
				lang: "zh_CN",
				context: this // 确保上下文正确
			})
		},
		streamRecordEnd() {
			//console.log('结束录音')
			this.animation = false
			voiceManager.stop()
			uni.vibrateShort()
			uni.showLoading({
				title: 'AI识别中...'
			})
		},
		initRecord() {
			// 实时识别结果
			voiceManager.onRecognize = (res) => {
				uni.hideLoading()
				if (res.result) {
					this.SceneDesc = res.result
				}
			}
			// 最终识别结果
			voiceManager.onStop = (res) => {
				uni.hideLoading()
				//console.log('识别结果', res)
				if (res.result) {
					this.SceneDesc = res.result
				} else {
					uni.showToast({ title: '未识别到内容', icon: 'none' })
				}
			}
			// 错误处理
			voiceManager.onError = (err) => {
				console.error('识别错误', err)
				this.animation = false
				uni.showToast({ title: '语音识别失败，请重试', icon: 'none',duration:3000 })
			}
		},
		resetRecord(){
			let that=this
			that.RecordData=''
		},
		confirmRecord(res){
			let that=this
			that.RecordModalName=''
			that.RecordData=res
		},
		cancelRecord(res){
			let that=this
			that.RecordModalName=''
		},
		onloadCheckRecordAuth(){
			uni.getSetting({
				success(res) {
					if (!res.authSetting['scope.record']) {
					// 请求权限
					uni.authorize({
					  scope: 'scope.record',
					  success() {
					  },
					  fail() {
						uni.showModal({
						  title: '权限不足',
						  content: '需要麦克风权限才能录音，请前往设置开启',
						  confirmText: '去设置',
						  success(res) {
							if (res.confirm) {
							  uni.openSetting(); // 打开设置页面
							}
						  }
						});
					  }
					});
				  } else {
				  }
				}
			});	
		},
		ShowRecordModal(){
			let that=this
			// that.RecordModalName='RecordModal'
			// 检查权限
			uni.getSetting({
			    success(res) {
					//console.log('setting：'+JSON.stringify(res))
			        if (!res.authSetting['scope.record']) {
			        // 请求权限
			        uni.authorize({
			          scope: 'scope.record',
			          success() {
			            that.RecordModalName = 'RecordModal'; // 显示录音组件
			          },
			          fail() {
			            uni.showModal({
			              title: '权限不足',
			              content: '需要麦克风权限才能录音，请前往设置开启',
			              confirmText: '去设置',
			              success(res) {
			                if (res.confirm) {
			                  uni.openSetting(); // 打开设置页面
			                }
			              }
			            });
			          }
			        });
			      } else {
			        that.RecordModalName = 'RecordModal'; // 已有权限，显示录音
			      }
			    }
			});
		},
		getPhoneNumber (e) {
			let that = this
			if(e.detail.errMsg == 'getPhoneNumber:ok') {
				const accountInfo = uni.getAccountInfoSync(); //获取appid
				////console.log('000000', accountInfo.miniProgram.appId);
				////console.log('12321', e)
				let encryptedData = e.detail.encryptedData;
				let iv = e.detail.iv;
				
				////console.log('0001',encryptedData)
				////console.log('0002',iv)
				const WXBizDataCrypt = require('@/common/WXBizDataCrypt.js')
				let pc = new WXBizDataCrypt(accountInfo.miniProgram.appId, that.session_key)
				let data = pc.decryptData(encryptedData, iv);
				////console.log('手机号码:', data.purePhoneNumber);
				that.requestData.Phone = data.purePhoneNumber
			} else {
				uni.showToast({
					title: '获取用户手机号失败',
					duration: 3000,
					icon: 'none'
				})
			}
		},
		getSessionKey(){
			let that=this
			//再拿一次code
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					
					let data={
						code:loginRes.code
					}
					let opts = {
						url: 'api/GetSessionKeyByCode',
						method: 'get'
					};
					request.httpRequest(opts,data).then(res => {
						////console.log("123131321312",res)
						that.session_key=res.data.msg
					});
				}
			});
		},
		GetQrcodeDeviceList(qrcodeId){
			console.log('GetQrcodeDeviceList')
			let that=this
			
			that.qrcodeDeviceList=[]
			//判断是否需要设备1
			let opts = {
				url: 'SpareApi/GetQrcodeDeviceList',
				method: 'get'
			};
			let params={
				qrcodeId:qrcodeId
			};
			uni.showLoading({
				title: '加载中'
			})
			request.httpTokenRequest(opts,params).then(res => {
				uni.hideLoading();
				if(res.data.code == 1){
					that.qrcodeDeviceList=res.data.data
				}else{
					//uni.showToast({ title: '点位设备架构获取失败', icon: '/static/cha.png' });
				}
			})
		},
		showQrcodeChoose(){
			uni.navigateTo({
				url: '/pages-device/repair/deviceListChoose'
			})
		},
		chooseSceneExperience(){
			uni.navigateTo({
				url: '/pages-others/SceneExperience'
			})
		},
		showQrcodeSelect(){
			let that=this
			that.qrcodeSeleceShow=true
		},
		confirmQrcode(data) {
			//console.log('confirmQrcode')
			//console.log(data)
			let that=this
			that.selectQrcodeEntity.id=data.id
			that.selectQrcodeEntity.name=data.name
						that.GetQrcodeDeviceList(data.id)			
		},
		chooseSceneUsers(){
			let that=this
			//打开弹窗
			let opts = {
				url: 'api/GetDepartmentTreeList',
				method: 'get'
			};
			uni.showLoading({
				title: '加载中'
			})
			let GetDepartmentTreeListPara={
				type:'all'
			}
			request.httpTokenRequest(opts,GetDepartmentTreeListPara).then(res => {
				uni.hideLoading();
				if(res.data.code == 1){
					that.treeUserList=res.data.data
					this.$refs.treePicker._show();
				}else{
					uni.showToast({ title: '人员架构获取失败', icon: '/static/cha.png' });
				}
			})
		},
		selectAssign(ids){
			let that=this
			that.SceneUserIds=[]
			that.requestData.sceneUserOrDepart=[]
			if(ids.length==0){
				//uni.showToast({ title:'请选择人员或部门', icon: 'none' });
				this.$refs.treePicker._hide();
			}else{
				that.SceneUserIds=ids
				//console.log(that.SceneUserIds)
				//最多12个字
				let chooseNames='';
				//that.SceneUserChooseStatus='已选择已选择已选择已选择'
				for(let i=0;i<ids.length;i++){
					let entity=ids[i]
					chooseNames=entity.name+','+chooseNames
				}
				if(chooseNames.indexOf(",")!=-1){
					chooseNames=chooseNames.substr(0,chooseNames.length-1)
				}
				if(chooseNames.length>=13){
					chooseNames=chooseNames.substr(0,11)+'...'
				}
				that.SceneUserChooseStatus=chooseNames
				that.requestData.sceneUserOrDepart=ids
			}
		},
	    async getLocationAndStorageSync(){
			let that=this
			
			uni.getLocation({
			  	type: 'gcj02',
			  	altitude: true,
			  	success(res) {
					var qqmapsdk = new QQMapWX({
						key:that.$request22.qqMapKey //自己申请的key
					});
					qqmapsdk.reverseGeocoder({
						location: {
							latitude:res.latitude,
							longitude: res.longitude
						},
						success(addressRes) {
							that.Location.address = addressRes.result.address;
						},
						fail(res) {
							//console.log(res)
						}
					});
			  	   }
			    })
				uni.getStorageSync({
					key:'JobId',
					success(res) {
						that.JobStorage.JobId=res.data.id;
						that.JobStorage.JobName=res.data.jobname;
					},fail(err) {
						
					}
				})
		},
	  	async getWaterMarkSettings(){
	  		let that=this
			let imageIndex= that.formData.findIndex(e => e.id === 'asdfdfgd')
	  		uni.getStorage({
	  		  	key: 'userdata',
	  		  	success: function (res1) {
					that.formData[imageIndex].watermark.UserName=res1.data.RealName
					that.requestData.Phone=res1.data.Phone
	  		  	}
	  		});
			uni.getLocation({
			  	type: 'gcj02',
			  	altitude: true,
			  	success(res) {
					that.requestData.Latitude=res.latitude.toString()
					that.requestData.Longitude=res.longitude.toString()
					that.formData[imageIndex].watermark.jingweidu=res.latitude+','+res.longitude
					var qqmapsdk = new QQMapWX({
						key:that.$request22.qqMapKey //自己申请的key
					});
					qqmapsdk.reverseGeocoder({
						location: {
							latitude:res.latitude,
							longitude: res.longitude
						},
						success(addressRes) {
							that.formData[imageIndex].watermark.address =  addressRes.result.address;
							that.Location.address = addressRes.result.address;
						},
						fail(res) {
							//console.log(res)
						}
					});
			  	   }
			})
			uni.getStorageSync({
				key:'JobId',
				success(res) {
					that.JobStorage.JobId=res.data.id;
					that.formData[imageIndex].watermark.JobName=res.data.jobname;
					that.JobStorage.JobName=res.data.jobname;
				},fail(err) {
					that.formData[imageIndex].watermark.JobName ='工单水印'
				}
			})
			
			uni.getStorage({
			  	key: 'userdata',
			  	success: function (res1) {
					that.formData[imageIndex].watermark.UserName=res1.data.RealName
			  	}
			});
	  		that.getTime()
			//that.getCustomerName()
	  	},
	  	getTime: function() {
	  		let that=this
			 let imageIndex= that.formData.findIndex(e => e.id === 'asdfdfgd')
	  		var date = new Date(),
	  			year = date.getFullYear(),
	  			month = date.getMonth() + 1,
	  			day = date.getDate(),
	  			hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
	  			minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
	  			second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	  		month >= 1 && month <= 9 ? (month = "0" + month) : "";
	  		day >= 0 && day <= 9 ? (day = "0" + day) : "";
	  		var timer = year + '年' + month + '月' + day + '日';
	  		var timer2 = hour + ':' + minute + ':' + second;
	  		that.formData[imageIndex].watermark.nowTime=timer+' '+timer2
	  	},
		async GetBaseConfig(QrcodeId){
			uni.showLoading({title: '配置加载中...'})
			return new Promise((resolve, reject) => {
				let id=''
				if(QrcodeId != '' && QrcodeId != undefined && QrcodeId != null){
					id=QrcodeId
				}
				let that=this
				let opts = {
					url: 'api/GetBaseConfigNew',
					method: 'get'
				};
				let params={
					qrcodeId:id
				}
				request.httpTokenRequest(opts,params).then(res => {
					uni.hideLoading()
					if(res.data.code == 1){
						let result=res.data.data.BaseData
						console.log('接口data：'+res.data.data.ShowSecondQrcodeDevice)
						that.ShowSecondQrcodeDevice=res.data.data.ShowSecondQrcodeDevice
						
						that.AddSceneChooseUserShow=res.data.data.AddSceneChooseUserShow
						that.IsQrcodeSceneRecodrd=res.data.data.IsQrcodeSceneRecodrd
						
						
						let resultData=[]
						if(result.length>0){
							
							let sceneTypeIndex=that.formData.findIndex(e => e.id === 'sada55sgh')
							for(let i=0;i<result.length;i++){
								let entity={'value':result[i].COnfigValue,'label':result[i].COnfigValue}
								resultData.push(entity)
							}
							
							that.formData[sceneTypeIndex].list=resultData
							
							that.formData[sceneTypeIndex].rules.value=result[0].COnfigValue
							that.formData[sceneTypeIndex].rules.label=result[0].COnfigValue
						}
						
						//加载最新的自定义字段
						let SceneTopicInfoList=res.data.data.SceneTopicInfoList
						if(SceneTopicInfoList!=null){
							if(SceneTopicInfoList.length>0){
								let list=[]
								let fromData=[]
								for(let i=0;i<SceneTopicInfoList.length;i++){
									list=[]
									let item=SceneTopicInfoList[i]
									//1 单选，2 多选，3数字，4文字
									if(item.TopicType==1||item.TopicType==2){
										let fromItem={}
										let rules={}
										for(let j=0;j<item.TopicOptionArry.length;j++){
											let listItem={}
											if(item.TopicType==1){
												listItem.value=item.TopicOptionArry[j]
												listItem.label=item.TopicOptionArry[j]
											}else{
												listItem.value=item.TopicOptionArry[j]
												listItem.name=item.TopicOptionArry[j]
											}
											list.push(listItem)
										}
										fromItem.id=item.Id;
										fromItem.placeholder=item.TopicTips;
										fromItem.label=item.TopicTitle;
										fromItem.type=item.TopicType==1?'radio':'checkbox';
										fromItem.list=list;
										rules.name='result'+i;
										rules.value='';
										rules.label='';
										rules.verify=item.Required==1?true:false;
										rules.errMess='';
										fromItem.rules=rules;
										that.formData.splice(that.formData.length-3,0,fromItem)
									}else if(item.TopicType==3){
										let fromItem={}
										fromItem.id=item.Id;
										if(item.TopicUnit!=''){
											fromItem.placeholder=item.TopicTips+'('+item.TopicUnit+')';
										}else{
											fromItem.placeholder=item.TopicTips;
										}
										
										fromItem.label=item.TopicTitle;
										fromItem.type='number';
										let rules={}
										rules.name='result'+i;
										rules.value='';
										rules.label='';
										rules.verify=item.Required==1?true:false;
										rules.errMess='';
										fromItem.rules=rules;
										that.formData.splice(that.formData.length-3,0,fromItem)
									}else if(item.TopicType==4){
										let fromItem={}
										fromItem.id=item.Id;
										fromItem.placeholder=item.TopicTips;
										fromItem.label=item.TopicTitle;
										fromItem.type='textarea';
										let rules={}
										rules.name='result'+i;
										rules.value='';
										rules.label='';
										rules.verify=item.Required==1?true:false;
										rules.errMess='';
										fromItem.rules=rules;
										that.formData.splice(that.formData.length-3,0,fromItem)
									}else if(item.TopicType==6){
										let fromItem={}
										fromItem.id=item.Id+'hfhg';
										fromItem.placeholder="请选择";
										fromItem.label=item.TopicTitle;
										fromItem.type='select';
										fromItem.show=false
										fromItem.title="请选择"
										
										fromItem.list=item.selectOptions
										let rules={}
										rules.name='result'+i;
										rules.value='';
										rules.label='';
										rules.verify=item.Required==1?true:false;
										rules.errMess='请选择'+item.TopicTitle;
										fromItem.rules=rules;
										that.formData.splice(that.formData.length-3,0,fromItem)
										
									}else if(item.TopicType==999){
										that.showPhone=true
										that.phoneVerify=item.Required==1?true:false;
										that.getSessionKey()
									}
								}
								uni.hideLoading();
							}
						}
						
						let videoIndex=that.formData.findIndex(e => e.id === 'asdf111gd')
						that.formData[videoIndex].url=this.$request22.baseUrl
						
						let imageIndex= that.formData.findIndex(e => e.id === 'asdfdfgd')
	  				    that.formData[imageIndex].watermark.customerName=res.data.data.UserName
	  				    //that.formData[imageIndex].watermark.chooseAlbum=res.data.data.SceneSelectAlbum
					}
				});
				// 执行异步操作
				setTimeout(() => {
					resolve();
				}, 1000);
			});
		},
		// 提交表单
		async sub() {
			let that=this
			if(that.isButtonDisabled1){return}
			that.isButtonDisabled1=true
			
			let imageIndex= that.formData.findIndex(e => e.id === 'asdfdfgd')
			let videoIndex=that.formData.findIndex(e => e.id === 'asdf111gd')
			this.$vervify(that.formData); //表单校验 成功会继续往下走 失败抛出异常
			const res = this.$submitForm(that.formData); //校验成功 获取表单值
			
			////console.log(res)
			let opts = {
				url: 'api/AddQrcodeScene',
				method: 'post'
			};
			if(!that.selectQrcodeEntity.id){
				uni.showToast({ title: '请选择点位', icon: 'none' });
				that.isButtonDisabled1=false
				return
			}
			if(!that.SceneDesc){
				uni.showToast({ title: '请输入描述信息', icon: 'none' });
				that.isButtonDisabled1=false
				return
			}
			if(that.showPhone&&that.phoneVerify){
				if(!that.requestData.Phone){
					uni.showToast({ title: '请获取您的手机号', icon: 'none' });
					that.isButtonDisabled1=false
					return
				}
			}
			that.requestData.DeviceId=that.chooseDeviceValue;
			that.requestData.Desc=that.SceneDesc;
			that.requestData.QrcodeId=that.selectQrcodeEntity.id;
			that.requestData.SceneType=res.SceneType;
			let images=[]
			if(this.formData[imageIndex].rules[0].value!=null&&this.formData[imageIndex].rules[0].value!=''){
				images.push('/'+this.$request22.QiNiuNameSpace+this.formData[imageIndex].rules[0].value.split(this.$request22.QiNiuNameSpace)[1])
			}
			if(this.formData[imageIndex].rules[1].value!=null&&this.formData[imageIndex].rules[1].value!=''){
				images.push('/'+this.$request22.QiNiuNameSpace+this.formData[imageIndex].rules[1].value.split(this.$request22.QiNiuNameSpace)[1])
			}
			if(this.formData[imageIndex].rules[2].value!=null&&this.formData[imageIndex].rules[2].value!=''){
				images.push('/'+this.$request22.QiNiuNameSpace+this.formData[imageIndex].rules[2].value.split(this.$request22.QiNiuNameSpace)[1])
			}
			that.requestData.Images=images;
			that.requestData.Video=this.formData[videoIndex].rules.value;
			
			//index  0     1    *  *  *    4    5     6
			//       点位  描述  *  *  *  照片 视频  类型
			//arr.splice(1, 1);
			// this.formData.splice(this.formData.findIndex(e => e.id === 'ukhjg'), 1)
			// this.formData.splice(this.formData.findIndex(e => e.id === 'asdfgf'), 1)
			this.formData.splice(this.formData.findIndex(e => e.id === 'asdfdfgd'), 1)
			this.formData.splice(this.formData.findIndex(e => e.id === 'asdf111gd'), 1)
			this.formData.splice(this.formData.findIndex(e => e.id === 'sada55sgh'), 1)
			
			let CustomFields=[]
			////console.log(JSON.stringify(this.formData))
			if(this.formData!=null&&this.formData.length>0){
				for(let j=0;j<this.formData.length;j++){
					let formEntity=this.formData[j]
					let newEntity={}
					newEntity.label=formEntity.label
					//1 text  2 phone  3radio  4checkbox  5number   6textarea   7select
					if(formEntity.type=='text'){
						newEntity.dataType=1
						newEntity.value=formEntity.rules.value
					}
					if(formEntity.type=='phone'){
						newEntity.dataType=2
						newEntity.value=formEntity.rules.value
					}
					if(formEntity.type=='radio'){
						newEntity.dataType=3
						newEntity.value=formEntity.rules.value
					}
					if(formEntity.type=='checkbox'){
						newEntity.dataType=4
						if(formEntity.rules.value.length>0){
							newEntity.value=formEntity.rules.value.join(",")
						}else{
							newEntity.value=""
						}
					}
					if(formEntity.type=='number'){
						newEntity.dataType=5
						newEntity.value=formEntity.rules.value
					}
					if(formEntity.type=='textarea'){
						newEntity.dataType=6
						newEntity.value=formEntity.rules.value
					}
					if(formEntity.type=='select'){
						newEntity.dataType=7
						newEntity.value=formEntity.rules.value
					}
					newEntity.isMustFill=formEntity.rules.verify
					newEntity.options=''
					CustomFields.push(newEntity)
				}
			}
			
			that.requestData.CustomFields=JSON.stringify(CustomFields)
			
			uni.showLoading({
				title: '上传中...'
			})
			let token =uni.getStorageSync('userdata').token;
			//console.log('RecordData:'+that.RecordData)
			if(that.RecordData!=''){
				//console.log(111)
				uni.uploadFile({
					url: this.$request22.baseUrl+'api/UploadFile?fileModule='+923, //仅为示例，非真实的接口地址
					filePath: that.RecordData,
					header:{
						'token': token,
					},
					name: 'fileList',
					method: 'post',
					success: (uploadFileRes) => {
						uni.hideLoading();
						//console.log(5)
						let result=JSON.parse(uploadFileRes.data)
						//console.log(result)
						if(result.code == 1){
							//console.log('result.data:'+result.data)
							that.requestData.RecordDataUrl=result.data
							request.httpTokenRequest(opts,that.requestData).then(res => {
								that.isButtonDisabled1=false
								if(res.data.code == 1){
									uni.showToast({ title:'添加成功', icon: '/static/success.png' });
									uni.getStorage({
										key: 'PageCur',
										success: function (res1) {
											setTimeout(() => {
												 uni.reLaunch({
													url: '/pages/index/tabbar?PageCur='+res1.data
												 });
											}, 0)
										},fail() {
											setTimeout(() => {
												 uni.reLaunch({
													url: '/pages/index/tabbar?PageCur=index'
												 });
											}, 0)
										}
									});
								}
								else{
									uni.showToast({ title: res.data.msg, icon: 'none' });
								}
							})
						}
					},fail() {
						uni.hideLoading();
						uni.showToast({ title:'录音上传失败', icon: 'none' });
						request.httpTokenRequest(opts,that.requestData).then(res => {
							that.isButtonDisabled1=false
							if(res.data.code == 1){
								uni.showToast({ title:'添加成功', icon: '/static/success.png' });
								uni.getStorage({
									key: 'PageCur',
									success: function (res1) {
										setTimeout(() => {
											 uni.reLaunch({
												url: '/pages/index/tabbar?PageCur='+res1.data
											 });
										}, 0)
									},fail() {
										setTimeout(() => {
											 uni.reLaunch({
												url: '/pages/index/tabbar?PageCur=index'
											 });
										}, 0)
									}
								});
							}
							else{
								uni.showToast({ title: res.data.msg, icon: 'none' });
							}
						})
					}
				});
			}else{
				//console.log(222)
				request.httpTokenRequest(opts,that.requestData).then(res => {
					that.isButtonDisabled1=false
					if(res.data.code == 1){
						uni.showToast({ title:'添加成功', icon: '/static/success.png' });
						uni.getStorage({
							key: 'PageCur',
							success: function (res1) {
								setTimeout(() => {
									 uni.reLaunch({
										url: '/pages/index/tabbar?PageCur='+res1.data
									 });
								}, 0)
							},fail() {
								setTimeout(() => {
									 uni.reLaunch({
										url: '/pages/index/tabbar?PageCur=index'
									 });
								}, 0)
							}
						});
					}
					else{
						uni.showToast({ title: res.data.msg, icon: 'none' });
					}
				})
			}
		},
		getQrcodeList(){
			let that=this
			that.qrcodeArry=[]
			that.requestData.Longitude=that.Location.longitude;
			that.requestData.Latitude=that.Location.latitude;
			let opts = {
				url: 'api/GetLatelyQrcode',
				method: 'get'
			};
			request.httpTokenRequest(opts,that.requestData).then(res => {
				if(res.data.code == 1){
					if(res.data.data.length>0){
						let firstQrcode=res.data.data[0]
						that.selectQrcodeEntity.id=firstQrcode.Id
						that.selectQrcodeEntity.name=firstQrcode.qrcode_title
						that.GetQrcodeDeviceList(firstQrcode.Id)
						
						for(let i = 0; i < res.data.data.length; i++) {
							let data = res.data.data[i];
							let listdata={}
							listdata.id=res.data.data[i].Id
							listdata.name=res.data.data[i].qrcode_title
							that.qrcodeArry.push(listdata)
						}
					}
				}
				else{
					uni.showToast({ title: res.data.msg, icon: 'none' ,duration:4000});
				}
			});
		},
		getSetting() {
			const that = this
			uni.getSetting({
			  success(res) {
				 ////console.log(res)
					if (res.authSetting['scope.userLocation']) {
						that.getLocation1()
					} else {
						that.getAuthorize()
					}
			  }
			})
		},
		//  获取用户的地理位置，
		getLocation1() {
			const that = this
			uni.getLocation({
				type: 'gcj02',
				altitude: true,
				success(res) {
					////console.log(that.log)
				}
			})
		},
		// 用户授权
		getAuthorize() {
			const that = this
			uni.authorize({
				scope: 'scope.userLocation',
				success(res) {
					///that.getLocation()
				},
				// 授权失败
				fail(err) {
					uni.showModal({
						title: '提示',
						content: '请授权位置您的位置!',
						showCancel: false,
						confirmText: '确认授权',
						success() {
							uni.openSetting({
								success(res) {
									////console.log(res)
								},
								fail(err) {
									////console.log(err)
								}
							})
						}
					})
				}
			})
		}
  },
};
</script>

<style lang="less">
.form-item .flex-row--c{
	width: 100%;
}
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .subform {
	left: 5%;
	bottom: 8%;
	width: 90%;
	text-align: center;
    padding: 20rpx 60rpx;
    border-radius: 18rpx;
    background-color: #0081ff;
	color: white;
  }
}

	.publish-goods-wrap {
		background: rgba(255, 255, 255, .5);
		padding: 24rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
	}

	.publish-goods-btn {
		margin: 24rpx;
		background: #0079FE;
		color: #FFFFFF;
		height: 82rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 82rpx;
	}

	.goods-empty-wrap {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 40%;
	}
	.content {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  justify-content: center;
	  //padding-top: 30rpx;
	}
	
	.chooseBox{
		width: 95%;
		background-color: #fff;
		margin: auto;
		margin-top: 10rpx;
		border-radius: 20rpx;
		padding: 27rpx 30rpx 27rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.titleleftBox{
			display: flex;
			align-items: center;
			width: 76%;
		}
		.titlerightBox{
			display: flex;
			align-items: right;
			font-size: 26rpx;
			//color:#0079FE;
			font-weight: 500;
			line-height: 40rpx;
			height: 40rpx;
		}
		.choose{
			padding-left: 10rpx;
			font-weight: 600;
			font-size: 28rpx;
			color: #000000;
		}
		.rapid{
			font-size: 28rpx;
			font-weight: 500;
			margin-left: 20rpx;
			color: #333;
			width: 70%;
			line-height: 60rpx;
		}
		.select-icon{
			float: right;
			border-bottom: 2upx solid #999;
			border-right: 2upx solid #999;
			width: 16upx;
			height: 16upx;
			transform: rotate(-45deg);
			margin-right: 30rpx;
		}
	}
	
	
	.chooseBoxTextArea {
		width: 95%;
		background-color: #fff;
		margin: auto;
		margin-top: 10rpx;
		border-radius: 20rpx;
		padding: 27rpx 30rpx 27rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.titleleftBox {
			width: 100%;
		}
		.choose {
			padding-left: 10rpx;
			font-weight: 600;
			font-size: 28rpx;
			color: #000000;
			display: flex;
			justify-content: space-between;
			align-items: center;
			line-height: 60rpx;
			.chooseLeft {
				// 靠左对齐
			}
			.chooseRightContainer {
				display: flex;
				align-items: center;
				.chooseMiddle {
					font-size: 26rpx;
					font-weight: 500;
					line-height: 60rpx;
					margin-left: 20rpx;
				}
				.chooseRight {
					font-size: 26rpx;
					font-weight: 500;
					line-height: 60rpx;
					margin-left: 20rpx;
				}
			}
		}
		.descTextArea {
			padding: 20rpx;
			width: 100%;
			font-size: 28rpx;
			height: 200rpx;
		}
		.holdToTalkButton {
			width: 100%;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			background-color: #F3F3F3;
			border-radius: 10rpx;
			font-size: 26rpx;
			color: #333;
			border: 1rpx solid #E7E7E7;
			transition: background-color 0.3s;
			&:active {
				background-color: #e0e0e0; /* 按钮按下时的背景色 */
			}
		}
	}
	// .chooseBoxTextArea{
	// 	width: 95%;
	// 	background-color: #fff;
	// 	margin: auto;
	// 	margin-top: 10rpx;
	// 	border-radius: 20rpx;
	// 	padding: 27rpx 30rpx 27rpx;
	// 	display: flex;
	// 	align-items: center;
	// 	justify-content: space-between;
	// 	.titleleftBox{
	// 		//display: flex;
	// 		//align-items: center;
	// 		width: 100%;
	// 	}
	// 	.titlerightBox{
	// 		display: flex;
	// 		align-items: right;
	// 		font-size: 24rpx;
	// 		color:#0079FE;
	// 		width: 100%;
	// 		font-weight: 500;
	// 		line-height: 40rpx;
	// 		height: 40rpx;
	// 	}
	// 	.choose{
	// 		padding-left: 10rpx;
	// 		font-weight: 600;
	// 		font-size: 28rpx;
	// 		color: #000000;
	// 		display: flex;
	// 		justify-content: space-between;
	// 		line-height: 60rpx;
	// 		.chooseRight{
	// 			font-size: 26rpx;
	// 			font-weight: 500;
	// 			line-height:60rpx;
	// 		}
	// 		.chooseMiddle{
	// 			font-size: 26rpx;
	// 			font-weight: 500;
	// 			line-height:60rpx;
	// 			margin-left: 20rpx;
	// 		}
	// 	}
	// 	.descTextArea{
	// 		padding: 20rpx;
	// 		width:100%;
	// 		font-size:28rpx;
	// 		height:200rpx;
	// 	}
	// 	.rapid{
	// 		font-size: 28rpx;
	// 		font-weight: 500;
	// 		margin-left: 20rpx;
	// 		color: #333;
	// 		width: 70%;
	// 	}
	// 	.select-icon{
	// 		float: right;
	// 		border-bottom: 2upx solid #999;
	// 		border-right: 2upx solid #999;
	// 		width: 16upx;
	// 		height: 16upx;
	// 		transform: rotate(-45deg);
	// 		margin-right: 30rpx;
	// 	}
	// }
	.chooseBoxPhone{
		width: 95%;
		background-color: #fff;
		margin: auto;
		margin-top: 10rpx;
		border-radius: 20rpx;
		padding: 47rpx 30rpx 27rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		.titleleftBox{
			display: flex;
			align-items: center;
			width: 100%;
		}
		.titlerightBox{
			display: flex;
			align-items: right;
			font-size: 26rpx;
			//color:#0079FE;
			font-weight: 500;
			line-height: 40rpx;
			height: 40rpx;
		}
		.choose{
			padding-left: 10rpx;
			font-weight: 600;
			font-size: 28rpx;
			color: #000000;
			min-width: 120rpx;
		}
		.rapid{
			font-size: 28rpx;
			font-weight: 500;
			margin-left: 20rpx;
			color: #333;
			width: 70%;
		}
		.rapid1{
			font-size: 28rpx;
			font-weight: 500;
			margin-left: 20rpx;
			color: #333;
			width: 70%;
		}
		.select-icon{
			float: right;
			border-bottom: 2upx solid #999;
			border-right: 2upx solid #999;
			width: 16upx;
			height: 16upx;
			transform: rotate(-45deg);
			margin-right: 30rpx;
		}
	}
	.vue-ref{
		padding-bottom: 0rpx !important;
	}
	
	
	/* 录音转文字动画-start */
	.prompt {
		width: 100%;
		height: 180rpx;
		position: fixed;
		bottom: 50vh;
	}
	
	.prompt text {
		position: absolute;
		bottom: 20rpx;
		color: white;
		left: calc(45%);
		animation: puls 1.5s infinite ease-in-out;
	}
	
	.dots-container {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80px;
		width: 45%;
		position: absolute;
		bottom: 0px;
		left: calc(27.5%);
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 20rpx;
		padding-bottom: 40rpx;
	}
	
	.dot {
		height: 28rpx;
		width: 28rpx;
		margin-right: 20rpx;
		border-radius: 20rpx;
		background-image: linear-gradient(#5396FF, #AEDAFF);
		animation: pulse 1.5s infinite ease-in-out;
	}
	
	.dot:last-child {
		margin-right: 0;
	}
	
	.dot:nth-child(1) {
		animation-delay: -0.3s;
	}
	
	.dot:nth-child(2) {
		animation-delay: -0.1s;
	}
	
	.dot:nth-child(3) {
		animation-delay: 0.1s;
	}
	
	@keyframes pulse {
		0% {
			transform: scale(0.8);
			background-color: #66A3FF;
			box-shadow: 0 0 0 0 rgba(102, 163, 255, 0.7);
		}
		50% {
			transform: scale(1.2);
			background-color: #ADD8FF;
			box-shadow: 0 0 0 10px rgba(174, 218, 255, 0);
		}
		100% {
			transform: scale(0.8);
			background-color: #66A3FF;
			box-shadow: 0 0 0 0 rgba(102, 163, 255, 0.7);
		}
	}
	
	@keyframes puls {
		0% { transform: translateY(0px) }
		50% { transform: translateY(-4px) }
		100% { transform: translateY(0px) }
	}
	/* 录音转文字动画-end */
</style>